/*
 * @Descripttion:
 * @version:
 * @Author: kl2018
 * @Date: 2020-03-17 09:11:31
 * @LastEditors: kl2018
 * @LastEditTime: 2020-10-26 10:45:15
 */

import React, { Component, Fragment } from 'react';
// import PropTypes from 'prop-types';
import { WeaTop, WeaRightMenu, WeaLocaleProvider, WeaDropdown, WeaTools } from 'ecCom';
import { inject, observer } from 'mobx-react';
import { WeaTableNew } from 'comsMobx';
import TabComponent from './TabComponent';
import OdocNoRightComponent from "./OdocNoRightComponent";
import { Button } from 'antd';
import { toJS } from 'mobx';

const { WeaTable } = WeaTableNew;
const { getLabel } = WeaLocaleProvider;
const { ButtonSelect } = WeaDropdown;

/*
topTitle=''  WeaTop的title
needTop 是否需要WeaTop组件
topBtns=[]
topBtns=
  [
    //普通的按钮
    {
      isDropDown:false,
      icon:<i className="icon-coms-search" /> //右键菜单选项的图标
      title:'跟踪',
      onClick:(keys,datas,clear)=>this.onTrack(keys,datas,clear),
      needCheck:true,
    },
    //下拉按钮
    // datas=[
    //   { key: '1', title: '批量提交',icon : <i className="icon-coms-Approval-o"/>},
    //   { key: '2', title: '批量提交',icon : <i className="icon-coms-Approval-o"/>},
    // ]
    {
      isDropDown:true,
      needCheck:true,
      datas:datas,
      btnOnClick:(key,selectedKeys,selectedDatas,clear)=>this.topBtnOnClick(key,selectedKeys,selectedDatas,clear),
      menuOnClick:key=>this.menuOnClick(key),
    },
  ]
 topBtns   WeaTop按钮  数据格式 ：数组  title：显示文字  methods：触发的方法   needCheck是否需要勾选才能点击
weaTopProps 支持WeaTop其他的属性覆盖

tabKey  选项卡的主键
tabUrl  获取tab数据的接口
tabParams={} 获取tab数据的参数
searchFormUrl 获取高级搜索的接口
searchParams={} 获取高级搜索的参数
baseSearchName='requestname' 基础搜索的name
searchType=[]  搜索类型  'base' 基本搜索  'advanced' 高级搜索
selectedTabKey = '' 默认选中的tabKey
weaTabProps 支持Weatab其他的属性覆盖
changeTabFun function 改变tab页签的时候需要执行的方法

tableUrl 获取列表数据的接口
tableParams 获取列表数据的参数
canGetTableData 是否获取高级搜索和获取列表分开获取
getColumns  需要自定义渲染的方法
onOperatesClick = null 操作
tableListNumber 当前页面数据的条数
weaTableProps 支持Weatab其他的属性覆盖
showCustomCol 是否显示列定制


rightMenuDatas 右键菜单数据 (默认会拿topBtns的数据)
moreRightDatas=[] 除了topBtns的数据还可以多添加的右键菜单的选项(属性和topBtns的数据一样)
rightMenuOtherProps={} 右键菜单其他的参数

this.refs.xxx.wrappedInstance.getTableDataBySearch() 通过搜索获取数据
this.refs.xxx.wrappedInstance.getTableDatasByDirect() 直接调用搜索方法获取数据
this.refs.tabComp.wrappedInstance.getTabData()  重选渲染tab页

*/

@inject('baseTableStore')
@observer
class BaseTableComp extends Component {
  constructor(props) {
    super(props);
    this.getTableDataBySearch = this.getTableDataBySearch.bind(this);
    this.getTableDatasByDirect = this.getTableDatasByDirect.bind(this);
    this.getTabData = this.getTabData.bind(this);
  }

  componentWillMount () {
    const { baseTableStore, tableUrl, tableParams, tableListNumber = -1 } = this.props;
    const { setMobxState } = baseTableStore;
    setMobxState({ tableUrl, tableParams, tableListNumber });
  }

  componentDidMount () {
    const { baseTableStore, tabKey, selectedTabKey, tabUrl, canGetTableData = true } = this.props;
    const { getTableDatas, setMobxState } = baseTableStore;
    let parmas = {};
    if (tabUrl && tabKey) {
      parmas[tabKey] = selectedTabKey || '0';
      canGetTableData && getTableDatas(parmas, false, false);
      !canGetTableData && setMobxState({ tableParams: parmas });
    } else {
      canGetTableData && getTableDatas(null, false, false);
    }
  }

  componentWillUnmount () {
    const { baseTableStore } = this.props;
    baseTableStore.init();
  }

  render () {
    const {
      className = 'odoc-tableBase',
      topTitle = '',
      getOtherDom = null,
      weaTopProps = {},
      needTop = true,
      rightMenuOtherProps = {},
      baseTableStore
    } = this.props;
    if (!baseTableStore.hasRight) { 
      return <OdocNoRightComponent/>
    }
    return (
      <div className={className}>
        <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@xih1mt`}
          datas={this.getRightMenuData()}
          {...rightMenuOtherProps}
        >

          {
            needTop &&
            <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@t8ufp9`}
              title={topTitle}
              icon={<i className="icon-coms-official" />}
              iconBgcolor="#f14a2d"
              buttons={this.getButtons()}
              {...weaTopProps}
            >
              {this.getContent()}
            </WeaTop>
          }

          {!needTop && this.getContent()}

        </WeaRightMenu>
        {typeof getOtherDom === 'function' ? getOtherDom() : null}
      </div>
    );
  }

  getButtons () {
    const { topBtns = [], baseTableStore, showCustomCol = false } = this.props;
    const { selectedRowKeys, selecteDatas, clearSelectKey, setMobxState, buttonKey } = baseTableStore;
    let buttons = [];
    topBtns.map((item, index) => {
      if (!item.isDropDown) {
        buttons.push(
          <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@wumr33@${index}`}
            type="primary"
            onClick={() => item.onClick(toJS(selectedRowKeys), toJS(selecteDatas), clearSelectKey)}
            disabled={item.needCheck ? !(toJS(selectedRowKeys).length > 0) : false}
          >{item.title}</Button>,
        );
      } else {
        item.datas.forEach((list) => {
          if (list.needCheck) {
            list.disabled = !(toJS(selectedRowKeys).length > 0);
          }
        });
        buttons.push(
          <ButtonSelect ecId={`${this && this.props && this.props.ecId || ''}_ButtonSelect@rz7jfm@${index}`}
            btnProps={{ disabled: item.needCheck ? !(toJS(selectedRowKeys).length > 0) : false }}
            datas={item.datas}
            selectedKey={buttonKey || item.datas[0].key}
            btnOnClick={key => item.btnOnClick(key, toJS(selectedRowKeys), toJS(selecteDatas), clearSelectKey)}
            menuOnClick={(key) => { setMobxState({ buttonKey: key }); item.menuOnClick(key); }}
          />,
        );
      }
    });
    if (showCustomCol) {
      buttons.push(
        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@pc4ru1@showcol`}
          type="primary"
          onClick={this.showCustomCol}
        >{getLabel('32535', '显示列定制')}</Button>,
      );
    }
    return buttons;
  }

  getRightMenuData () {
    const { topBtns = [], rightMenuDatas, baseTableStore, moreRightDatas = [], showCustomCol = false, showExportTable = false } = this.props;
    const { selectedRowKeys, selecteDatas, clearSelectKey, clear } = baseTableStore;
    if (rightMenuDatas) return rightMenuDatas;
    let datas = [];
    let key = 0;
    topBtns.map((item) => {
      let data = {};
      if (item.datas) {
        item.datas.map((i) => {
          if (item.buttonKey == i.key) {
            data = {
              key: `${key}`,
              disabled: item.needCheck ? !(toJS(selectedRowKeys).length > 0) : false,
              onClick: () => item.btnOnClick(i.key, toJS(selectedRowKeys), toJS(selecteDatas), clear),
              content: i.show,
              icon: i.icon,
            };
            datas.push(data);
            key++;
          }
        });
      } else {
        data = {
          key: `${key}`,
          disabled: item.needCheck ? !(toJS(selectedRowKeys).length > 0) : false,
          onClick: () => item.onClick(toJS(selectedRowKeys), toJS(selecteDatas), clearSelectKey),
          content: item.title,
          icon: item.icon,
        };
        key++;
        datas.push(data);
      }
    });

    moreRightDatas.map((item) => {
      const data = {
        key: `${key}`,
        disabled: item.needCheck ? !(toJS(selectedRowKeys).length > 0) : false,
        onClick: () => item.onClick(toJS(selectedRowKeys), toJS(selecteDatas), clearSelectKey),
        content: item.title,
        icon: item.icon,
      };
      key++;
      datas.push(data);
    });

    datas.push(
      {
        key: `${key}`,
        disabled: false,
        onClick: () => this.getTableDataBySearch({}, false, false),
        content: getLabel('388113', '搜索'),
        icon: <i className="icon-coms-search" />,
      },
    );

    if (showCustomCol) {
      key++;
      datas.push(
        {
          key: `${key}`,
          disabled: false,
          onClick: this.showCustomCol,
          content: getLabel('32535', '显示列定制'),
          icon: <i className="icon-coms-home" />,
        },
      );
    }
    if (showExportTable) {
      key++;
      datas.push(
        {
          key: `${key}`,
          disabled: false,
          onClick: this.exportAll,
          content: getLabel('28343', '导出Excel'),
          icon: <i className="icon-coms-export" />,
        },
      );
    }
    return datas;
  }

  // 通过搜索  获取列表的方法
  getTableDataBySearch (params = {}, onlyParams, covered) {
    this.refs.tabComp.wrappedInstance.onClickSearchBtn(params, onlyParams, covered);
  }

  // 直接调用  获取数据的方法
  getTableDatasByDirect (params = {}, onlyParams, covered, saveParams) {
    const { baseTableStore } = this.props;
    baseTableStore.getTableDatas(params, onlyParams, covered, saveParams);
  }

  // 获取tab页签的方法
  getTabData () {
    this.refs.tabComp.wrappedInstance.getTabData();
  }

  // 重置高级搜索form保单
  resetForm () {
    this.refs.tabComp.wrappedInstance.resetForm();
  }

  // 获取高级搜索
  getSearchFormItem (params) {
    return this.refs.tabComp.wrappedInstance.getSearchFormItem(params);
  }

  getContent () {
    const {
      tabUrl,
      searchFormUrl,
      getColumns,
      tabKey,
      selectedTabKey = '0',
      tabParams = {},
      searchParams = {},
      baseSearchName = 'requestname',
      // onOperatesClick = null,
      searchType = [],
      weaTabProps = {},
      weaTableProps = {},
      baseTableStore,
      changeTabFun = null,
      // initGetTabData = true,
    } = this.props;
    const { getTableDatas, tableStore, selectedRowKeys, tableOnSelect } = baseTableStore;
    return (
      <Fragment ecId={`${this && this.props && this.props.ecId || ''}_Fragment@flk7cm`}>
        <TabComponent ecId={`${this && this.props && this.props.ecId || ''}_TabComponent@nfcpxy`}
          tabKey={tabKey}
          getDataList={getTableDatas}
          baseSearchName={baseSearchName}
          searchType={searchType}
          tabUrl={tabUrl}
          tabParams={tabParams}
          getFormUrl={searchFormUrl}
          searchParams={searchParams}
          selectedTabKey={selectedTabKey}
          changeTabFun={changeTabFun}
          ref="tabComp"
          {...this.props}
          {...weaTabProps}
        />

        <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@4lyqiw`}
          comsWeaTableStore={tableStore}
          getColumns={getColumns || null}
          rowSelection={{
            selectedRowKeys,
            onChange: tableOnSelect,
          }}
          onOperatesClick={this.onOperatesClick}
          needScroll
          hasOrder
          {...weaTableProps}
        />
      </Fragment>
    );
  }

  exportAll = () => {
    const { baseTableStore,
      // fileName = '', topTitle = ''
    } = this.props;
    const { sessionkey } = baseTableStore;
    // const filename = fileName ? fileName : topTitle;
    WeaTools.callApi('/api/ec/dev/table/export', 'POST', { dataKey: sessionkey, filetype: '', filename: '' }).then(
      result => window.location.href = result.url,
    );
  }

  showCustomCol = () => {
    const { baseTableStore } = this.props;
    const { tableStore } = baseTableStore;
    tableStore.setColSetVisible(true);
    tableStore.tableColSet(true);
  }

  onOperatesClick = (record, index, operate, flag) => {
    const { onOperatesClick } = this.props;
    onOperatesClick(record, flag)
  }

}

// BaseTableComp.propTypes = {
//   prefix: PropTypes.string,
//   topTitle: PropTypes.string.isRequired,
//   topBtns: PropTypes.array,
//   tabUrl: PropTypes.string,
//   searchFormUrl: PropTypes.string,
//   getColumns: PropTypes.func,
//   tabKey: PropTypes.string,
//   selectedTabKey: PropTypes.string,
//   tabParams: PropTypes.object,
//   searchParams: PropTypes.object,
//   baseSearchName: PropTypes.object,
//   onOperatesClick: PropTypes.func,
//   getOtherDom: PropTypes.element,
//   searchType: PropTypes.array,
//   weaTopProps: PropTypes.object,
//   weaTabProps: PropTypes.object,
//   weaTableProps: PropTypes.object,
// };

export default BaseTableComp;
